package ch02sl.sz.sz3;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.util.Iterator;

public class XMLParseAdd {

    public  void showPhoneInfo() {
        Document doc = null;
        try {
            SAXReader saxReader = new SAXReader();
            doc = saxReader.read(new File("src/test/java/ch02sl/sz/PhoneInfo.xml"));
        }
         catch (DocumentException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        Element root = doc.getRootElement();
        Element newNode = root.addElement(  "Brand");
        Element newNode1 = newNode.addElement(  "Type");
        newNode.addAttribute( "name", "三星");
        newNode1.addAttribute(  "name",  "NoteX");

        for (Iterator iterator = root.elementIterator(); iterator.hasNext(); ) {
           Element brandEle = (Element) iterator.next();
            System.out.println("品牌："+brandEle.attributeValue("name"));
            for (Iterator itType = brandEle.elementIterator();itType.hasNext();){
                Element typeEle = (Element) itType.next();
                System.out.println("\t型号："+typeEle.attributeValue("name"));
            }
        }
        // 保存修改后的XML文件
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        try {
            XMLWriter writer = new XMLWriter(new FileWriter("src/test/java/ch02sl/sz/PhoneInfo.xml"), format);
            writer.write(doc);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        XMLParseAdd parse = new XMLParseAdd();
        parse.showPhoneInfo();
    }
}
